package com.grape.action.realm;

import java.util.List;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.grape.dao.system.PermissionRepository;
import com.grape.dao.system.RoleRepository;
import com.grape.domain.system.Permission;
import com.grape.domain.system.Role;
import com.grape.domain.system.User;
import com.grape.service.system.UserService;

public class BosRealm extends AuthorizingRealm {

	@Autowired
	private PermissionRepository pr;
	
	@Autowired
	private RoleRepository rr;
	
	@Autowired
	private UserService us;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection shiro) {
		// 厉害了,我在配置了ehcache缓存后以为登录一个权限大的用户再登录小权限因为权限已经缓存会出bug，需要在登录处清除缓存，结果没事！！！！内部肯定做了处理
		System.out.println("shiro权限管理");
		
		
		// 权限糖，收集用户角色与权限做判断
		SimpleAuthorizationInfo sa = new SimpleAuthorizationInfo();
		
		// 根据当前登录用户查询权限,在session里
		Subject subject = SecurityUtils.getSubject();
		User user = (User)subject.getPrincipal();
		
		// 后门
		if (user.getUsername().equals("admin")) {
			List<Role> findAll = rr.findAll();
			for (Role role : findAll) {
				sa.addRole(role.getKeyword());
			}
			
			List<Permission> findAll2 = pr.findAll();
			for (Permission permission : findAll2) {
				sa.addStringPermission(permission.getKeyword());
			}
			
			return sa;
		}
		
		// 收集
		for (Role role : user.getRoles()) {
			Set<Permission> permissions = role.getPermissions();
			for (Permission permission : permissions) {
				sa.addStringPermission(permission.getKeyword());
			}
			
			sa.addRole(role.getKeyword());
		}
		
		
		
		return sa;
	}

	@Override	// 校验是否可以登录
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("shiro登录认证");
		
		
		UsernamePasswordToken tk = (UsernamePasswordToken)token;
		User user = us.findByUsername(tk.getUsername());
		
		// 登录用户名错误
		if (user==null) {
			return null;
		
		// 如登陆成功则留用做后续权限验证，对象存到session，密码校验失败则抛异常，getName是类名是session——key的一部分
		}else {
			return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
		}
		
		
	}

}
